package Thread;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/****
 * 生产者消费者模型
 */
public class ProducerAndConsumer {

    public static volatile BlockingQueue bq = new ArrayBlockingQueue(10);

    public static void main(String[] args) {
        Thread producer = new Thread(new Producer(bq, 10));
        Thread consumer = new Thread(new Consumer(bq, 10));
        producer.start();
        consumer.start();
    }


}

class Producer implements Runnable {

    private BlockingQueue bq;
    private int size = 0;

    Producer(BlockingQueue b, int size) {
        bq = b;
        this.size = size;
    }

    @Override
    public void run() {

        while (true) {
            if (bq.isEmpty() || bq.size() <size) {
                int nu =  new Random().nextInt(size) + 1;
                bq.add(nu);
                System.out.println("生产了:-----"+ nu);

            }
//            try {
//                Thread.currentThread().sleep(1000l);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

        }

    }
}

class Consumer implements Runnable {
    private BlockingQueue bq;
    private int size = 0;

    Consumer(BlockingQueue b, int size) {
        bq = b;
        this.size = size;
    }

    @Override
    public void run() {
        while (true) {
            if (!bq.isEmpty() && bq.size() == size) {
                for (int i = 0; i < size; i++) {
                    try {
                        System.out.println("消费了：" + bq.take());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}


